package com.temi.demo.net;

import android.text.TextUtils;

import com.temi.demo.constants.URLConstants;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by coco on 2018/3/14.
 */

public class NetManager {

    private static NetManager netManager;
    private Retrofit retrofit;
    private OkHttpClient okHttpClient;

    public static NetManager getInstance() {
        if (netManager == null) {
            synchronized (NetManager.class) {
                netManager = new NetManager();
            }
        }
        return netManager;
    }

    public Retrofit getRetrofit() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .client(getOkHttpClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(URLConstants.BASE_TEST_URL)
                    .build();
        }
        return retrofit;
    }

    private OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient();
        }

        OkHttpClient.Builder httpClient = okHttpClient.newBuilder();
        httpClient.addNetworkInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request original = chain.request();
                Request request = original.newBuilder()
                        .header("App-Type", "ANDROID")
                        .header("App-Version", "1.0")
                        .build();

                return chain.proceed(request);
            }
        });

        return httpClient.build();
    }
}
